const express = require('express')
const router = express.Router()
const {getDb, saveDb} = require('../utils/db')


router.get('/task',async (req,res)=>{
  try {
    const tasksDB = await getDb("../mock/task.json");
    console.log(req.query.kanbanId);
    const tasks = tasksDB.filter(kanban => kanban.kanbanId === +req.query.kanbanId)
    // const tasks = tasksDB.filter(kanban => console.log(kanban.kanbanId))
    console.log(tasks);
    res.status(200).json(tasks)
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
})

router.get('/tasks',async (req,res)=>{
  try {
    const tasksDB = await getDb("../mock/task.json");
    res.status(200).json(tasksDB)
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
})


router.post('/tasks',async (req,res)=>{
  try {
    const newtask = req.body;
    console.log(newtask);
    if(!newtask.name){
      return res.status(401).json({
        error:'请添加任务名'
      })
    } 
    let tasksDB = await getDb("../mock/task.json");
    let lasttask = tasksDB[tasksDB.length -1]
    if(lasttask === undefined){
      console.log('没有初始值');
      lasttask = new Object()
      lastkanban.ownerId = 193361109
    }
    newtask.kanbanId = +newtask.kanbanId
    newtask.id = lasttask.id ? lasttask.id +1 : 1;
    newtask.created = new Date().getTime()
    tasksDB.push(newtask)

    await saveDb(tasksDB,"../mock/task.json")
    tasksDB = await getDb("../mock/task.json");
    res.status(200).json(tasksDB)
  } catch (error) {
    res.status(500).json({
      error:error.message
    })
  }
})

router.patch('/tasks/:taskId',async (req,res)=>{
  try {
    let tasks =await getDb("../mock/task.json")
    const gettask = tasks.find(task => task.id === +req.params.taskId)
    const gettaskInedx = tasks.findIndex(task => task.id === +req.params.taskId)
    if(gettaskInedx === -1){
      return res.status(402).json("没有数据，先添加！")
    }

    const newtask = (req.body);
    newtask.processorId = +newtask.processorId
    tasks[gettaskInedx] = {...gettask,...newtask}
   
    await saveDb(tasks,"../mock/task.json")
    tasks =await getDb("../mock/task.json")

    res.status(200).json(tasks)
  } catch (error) {
  }
})

router.delete('/tasks/:taskId',async (req,res)=>{
  const taskDB =await getDb("../mock/task.json")
  const gettaskInedx = taskDB.findIndex(kanban => kanban.id === +req.params.taskId);
  if(gettaskInedx ===-1){
    return res.status(402).json('找不到要删除的内容')
  }
  taskDB.splice(gettaskInedx,1)
  await saveDb(taskDB,"../mock/task.json")
  res.status(200).send('删除成功')
})
module.exports = router